<?php
	/**
	 * Virtualising an environment with this class.
	 * @author IMP
	 */
	
	class Environment {		
		public static function getTrace(){
			$trace = debug_backtrace(false);
			unset($trace[0]);
			return array_values($trace);
		}
		
		private static $variables = array();
		
		public static function set($a, $b, $c = null){
			if($c !== null){
				$tag = $a;
				$name = $b;
				$value = $c;
			}else{
				$tag = 'global';
				$name = $a;
				$value = $b;
			}
			
			self::$variables[$tag][$name] = $value;
		}
		
		public static function get($a, $b = null){
			if(!empty($b)){
				$tag = $a;
				$name = $b;
			}else{
				$tag = 'global';
				$name = $a;
			}
			
			if(!empty(self::$variables[$tag][$name])){
				return self::$variables[$tag][$name];
			}else{
				throw new EntryNotFoundException('Environment variable "' . $name . '" of tag "' . $tag . '" does not exist.');
			}
		}
		
		private static $shutdownCallbacks = array(), $shutdownCallbacksError = array();
		
		public static function addShutdownCallback($cb, $ignoreErrors = false){
			if(is_callable($cb)){
				if($ignoreErrors){
					self::$shutdownCallbacksError[] = $cb;
				}else{
					self::$shutdownCallbacks[] = $cb;
				}
			}else{
				throw new ParameterException('$cb', array('valid callback string', 'valid callback array', 'callable object'), $cb);
			}
		}
		
		public static function __shutdown(){
			$it = new IniTransformer(self::$variables);
			
			
			foreach(self::$shutdownCallbacksError as $cb){
				try {
					call_user_func($cb);
				}catch(Exception $e){
					echo 'Exception while shutting down: ' . $e;
				}
			}
			
			if(ErrorCapturer::getExceptionsCaught() == 0){
				foreach(self::$shutdownCallbacks as $cb){
					try {
						call_user_func($cb);
					}catch(Exception $e){
						echo 'Exception while shutting down: ' . $e;
					}
				}
			}
		}
	}
?>